package com.mzba.place.fragment;

import java.lang.ref.WeakReference;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragment;
import com.mzba.place.R;
import com.mzba.place.db.UserTable;
import com.mzba.place.entity.RegisterEntity;
import com.mzba.place.ui.MainActivity;
import com.mzba.place.ui.MyReportListActivity;
import com.mzba.place.ui.UserInfoActivity;
import com.mzba.place.utils.StringUtil;
import com.mzba.place.utils.Utils;

public class SlidingSettingFragment extends SherlockFragment {

	private ListView listView;
	private ImageView avatarImageView;
	private TextView usernameView;
	private MainActivity mainActivity;
	private RelativeLayout userLayout;
	
	private CautionsFragment settingFragment;
	private HelpFragment helpFragment;
	private AboutFragment aboutFragment;
	private MyReportsFragment myReportsFragment;
	private MyStarFragment myStarFragment;
	private SafecardFragment safecardFragment;
	private MyNotificationFragment myNotificationFragment;
	
	private RegisterEntity entry;
	private WeakReference<Bitmap> avatarBitmap = null;
	private UpdateAvatarReceiver receiver;
	
//	private HeaderListViewAdapter listAdapter;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mainActivity = (MainActivity) getSherlockActivity();
		IntentFilter filter = new IntentFilter();
		filter.addAction("update_avatar");
		receiver = new UpdateAvatarReceiver();
		mainActivity.registerReceiver(receiver, filter);
	}
	
	public void refreshUserInfo() {
		setUserinfoView();
	}
	
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_sm_list, null);
		userLayout = (RelativeLayout) view.findViewById(R.id.user_layout);
		listView = (ListView) view.findViewById(R.id.list);
		avatarImageView = (ImageView) view.findViewById(R.id.user_avatar);
		userLayout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(mainActivity, UserInfoActivity.class);
				intent.putExtra("avatar", entry.getAvatar_url());
				intent.putExtra("username", entry.getUsername());
				startActivity(intent);
			}
		});
		usernameView = (TextView) view.findViewById(R.id.user_name);
		setUserinfoView();
		return view;
	}
	
	private void setUserinfoView() {
		try {
			UserTable ut = new UserTable(mainActivity);
			entry = ut.get();
			if (StringUtil.isNotBlank(entry.getUsername())) {
				usernameView.setText(entry.getUsername());
			}
			if (StringUtil.isNotBlank(entry.getAvatar_url())) {
				new Thread() {
					public void run() {
						avatarBitmap = new WeakReference<Bitmap>(Utils.getBitmap(mainActivity, entry.getAvatar_url()));
						mainActivity.runOnUiThread(new Runnable() {
							
							@Override
							public void run() {
								if (avatarBitmap.get() != null) {
									avatarImageView.setImageBitmap(Utils.toRoundBitmap(avatarBitmap.get()));
								}
							}
						});
					};
				}.start();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		NavFragmentItemAdapter adapterIndex = new NavFragmentItemAdapter(mainActivity);
		adapterIndex.add(new NavFragmentItem(mainActivity.getString(R.string.fragment_map), R.drawable.sm_map));
		adapterIndex.add(new NavFragmentItem(mainActivity.getString(R.string.fragment_safecard), R.drawable.safe));
		adapterIndex.add(new NavFragmentItem(mainActivity.getString(R.string.fragment_noti), R.drawable.sm_noti));
		adapterIndex.add(new NavFragmentItem(mainActivity.getString(R.string.my_report), R.drawable.sm_report));
		adapterIndex.add(new NavFragmentItem(mainActivity.getString(R.string.my_stas), R.drawable.sm_star));
		adapterIndex.add(new NavFragmentItem(mainActivity.getString(R.string.fragment_setting), R.drawable.sm_tips));
		adapterIndex.add(new NavFragmentItem(mainActivity.getString(R.string.fragment_help), R.drawable.sm_help));
//		listAdapter.addSection("首页", adapterIndex);
		
//		NavFragmentItemAdapter adapterMy = new NavFragmentItemAdapter(mainActivity);
//		adapterMy.add(new NavFragmentItem(mainActivity.getString(R.string.my_comment), R.drawable.my_comments));
//		adapter.add(new NavFragmentItem(mainActivity.getString(R.string.my_attention), R.drawable.my_votes));
//		listAdapter.addSection("我的操作", adapterMy);
		
//		NavFragmentItemAdapter adapterHelp = new NavFragmentItemAdapter(mainActivity);
//		adapterHelp.add(new NavFragmentItem(mainActivity.getString(R.string.fragment_setting), R.drawable.setting));
//		adapter.add(new NavFragmentItem(mainActivity.getString(R.string.fragment_noti), R.drawable.my_noti));
//		adapterHelp.add(new NavFragmentItem(mainActivity.getString(R.string.fragment_help), R.drawable.sm_help));
//		adapter.add(new NavFragmentItem(mainActivity.getString(R.string.fragment_about), R.drawable.about));
//		listAdapter.addSection("管理", adapterHelp);
		
		listView.setAdapter(adapterIndex);
//		listView.setAdapter(listAdapter);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				mainActivity.menu.clear();
				mainActivity.getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
		        NavFragmentItem item = (NavFragmentItem) listView.getAdapter().getItem(arg2);
		        if (item.tag.equals(mainActivity.getString(R.string.fragment_map))) {
		        	mainActivity.currentFragment = new Fragment();
		        	mainActivity.getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
//		        	if (mainActivity.currentFragment != mainActivity.getHomeFragment()) {
//		        		if (mainActivity.getHomeFragment() == null) {
//		        			HomeFragment homeFragment = new HomeFragment();
//		        			mainActivity.setHomeFragment(homeFragment);
//		        		}
//		        		mainActivity.getHomeFragment().firstReportTime = false;
//		        		mainActivity.getHomeFragment().firstReportType = false;
//		        		FragmentNavigation.replace(mainActivity, mainActivity.getHomeFragment(), R.id.content, "homeFragment");
//		        		mainActivity.currentFragment = mainActivity.getHomeFragment();
//		        		mainActivity.setMapMenu();
//		        	}
		        	
		        	mainActivity.getSlidingMenu().toggle();
		        } else if (item.tag.equals(mainActivity.getString(R.string.fragment_setting))) {
		        	if (mainActivity.currentFragment != settingFragment) {
		        		if (settingFragment == null) {
		        			settingFragment = new CautionsFragment();
		        		}
		        		FragmentNavigation.replace(mainActivity, settingFragment, R.id.content, "settingFragment");
		        		mainActivity.currentFragment = settingFragment;
//		        		mainActivity.menu.clear();
		        		
		        	}
		        	mainActivity.setSettingMenu();
		        	mainActivity.getSlidingMenu().toggle();
		        } else if (item.tag.equals(mainActivity.getString(R.string.fragment_help))) {
		        	if (mainActivity.currentFragment != helpFragment) {
		        		if (helpFragment == null) {
		        			helpFragment = new HelpFragment();
		        		}
		        		FragmentNavigation.replace(mainActivity, helpFragment, R.id.content, "helpFragment");
		        		mainActivity.currentFragment = helpFragment;
//		        		mainActivity.menu.clear();
		        		mainActivity.actionBar.setTitle(mainActivity.getString(R.string.fragment_help));
		        	}
		        	mainActivity.getSlidingMenu().toggle();
		        } else if (item.tag.equals(mainActivity.getString(R.string.fragment_about))) {
		        	if (mainActivity.currentFragment != aboutFragment) {
		        		if (aboutFragment == null) {
		        			aboutFragment = new AboutFragment();
		        		}
		        		FragmentNavigation.replace(mainActivity, aboutFragment, R.id.content, "aboutFragment");
		        		mainActivity.currentFragment = aboutFragment;
//		        		mainActivity.menu.clear();
		        	}
		        	mainActivity.getSlidingMenu().toggle();
		        } else if (item.tag.equals(mainActivity.getString(R.string.my_report))) { //上报
		        	if (mainActivity.currentFragment != myReportsFragment) {
		        		if (myReportsFragment == null) {
		        			myReportsFragment = new MyReportsFragment();
		        		}
		        		FragmentNavigation.replace(mainActivity, myReportsFragment, R.id.content, "myReportsFragment");
		        		mainActivity.currentFragment = myReportsFragment;
//		        		mainActivity.menu.clear();
		        	}
		        	mainActivity.getSlidingMenu().toggle();
		        	mainActivity.actionBar.setTitle(mainActivity.getString(R.string.my_report));
//		        	Intent intent = new Intent(mainActivity, MyReportListActivity.class);
//					intent.putExtra("type", 0);
//					mainActivity.startActivity(intent);
		        } else if (item.tag.equals(mainActivity.getString(R.string.my_comment))) {//评论
		        	Intent intent = new Intent(mainActivity, MyReportListActivity.class);
					intent.putExtra("type", 3);
					mainActivity.startActivity(intent);
		        } else if (item.tag.equals(mainActivity.getString(R.string.my_attention))) {//支持
		        	Intent intent = new Intent(mainActivity, MyReportListActivity.class);
					intent.putExtra("type", 1);
					mainActivity.startActivity(intent);
		        } else if (item.tag.equals(mainActivity.getString(R.string.my_stas))) {//收藏
//		        	Intent intent = new Intent(mainActivity, MyReportListActivity.class);
//					intent.putExtra("type", 2);
//					mainActivity.startActivity(intent);
		        	if (mainActivity.currentFragment != myStarFragment) {
		        		if (myStarFragment == null) {
		        			myStarFragment = new MyStarFragment();
		        		}
		        		FragmentNavigation.replace(mainActivity, myStarFragment, R.id.content, "myStarFragment");
		        		mainActivity.currentFragment = myStarFragment;
//		        		mainActivity.menu.clear();
		        	}
		        	mainActivity.getSlidingMenu().toggle();
		        	mainActivity.actionBar.setTitle(mainActivity.getString(R.string.my_stas));
		        } else if (item.tag.equals(mainActivity.getString(R.string.fragment_noti))) {//通知
		        	if (mainActivity.currentFragment != myNotificationFragment) {
		        		if (myNotificationFragment == null) {
		        			myNotificationFragment = new MyNotificationFragment();
		        		}
		        		FragmentNavigation.replace(mainActivity, myNotificationFragment, R.id.content, "myNotificationFragment");
		        		mainActivity.currentFragment = myNotificationFragment;
//		        		mainActivity.menu.clear();
		        	}
		        	mainActivity.setAllNotificationMenu();
		        	mainActivity.actionBar.setTitle(mainActivity.getString(R.string.fragment_noti));
		        	mainActivity.getSlidingMenu().toggle();
		        } else if (item.tag.equals(mainActivity.getString(R.string.fragment_safecard))) {//安全卡
//		        	Intent intent = new Intent(mainActivity, SafecardActiviy.class);
//		        	mainActivity.startActivity(intent);
		        	if (mainActivity.currentFragment != safecardFragment) {
		        		if (safecardFragment == null) {
		        			safecardFragment = new SafecardFragment();
		        		}
		        		FragmentNavigation.replace(mainActivity, safecardFragment, R.id.content, "safecardFragment");
		        		mainActivity.currentFragment = safecardFragment;
//		        		mainActivity.menu.clear();
		        	}
		        	mainActivity.getSlidingMenu().toggle();
		        	mainActivity.actionBar.setTitle(mainActivity.getString(R.string.fragment_safecard));
		        }
			}
		});
	}

	private class NavFragmentItem {
		public String tag;
		public int iconRes;
		public NavFragmentItem(String tag, int iconRes) {
			this.tag = tag; 
			this.iconRes = iconRes;
		}
	}

	public class NavFragmentItemAdapter extends ArrayAdapter<NavFragmentItem> {

		public NavFragmentItemAdapter(Context context) {
			super(context, 0);
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = LayoutInflater.from(getContext()).inflate(R.layout.fragment_sm_list_item, null);
			}
			ImageView icon = (ImageView) convertView.findViewById(R.id.row_icon);
			icon.setImageResource(getItem(position).iconRes);
			TextView title = (TextView) convertView.findViewById(R.id.row_title);
			title.setText(getItem(position).tag);

			return convertView;
		}
	}
	
//	public class HeaderListViewAdapter extends BaseAdapter {
//		
//		public final Map<String,Adapter> sections = new LinkedHashMap<String,Adapter>();
//		public final ArrayAdapter<String> headers;
//		public final static int TYPE_SECTION_HEADER = 0;
//		
//		public HeaderListViewAdapter() {
//			headers = new ArrayAdapter<String>(mainActivity, R.layout.list_header_image, R.id.list_header_title);
//		}
//		
//		public void addSection(String section, Adapter adapter) {
//			this.headers.add(section);
//			this.sections.put(section, adapter);
//		}
//		
//		@Override
//		public Object getItem(int position) {
//			for (Object section : this.sections.keySet()) {
//				Adapter adapter = sections.get(section);
//				int size = adapter.getCount() + 1;
//
//				if (position == 0) {
//					return section;
//				}
//				if (position < size) {
//					return adapter.getItem(position - 1);
//				}
//				// otherwise jump into next section
//				position -= size;
//			}
//			return null;
//		}
//
//		@Override
//		public int getCount() {
//			// total together all sections, plus one for each section header
//			int total = 0;
//			for(Adapter adapter : this.sections.values()) {
//				total += adapter.getCount() + 1;
//			}
//			return total;
//		}
//
//		public int getViewTypeCount() {
//			// assume that headers count as one, then total all sections
//			int total = 1;
//			for(Adapter adapter : this.sections.values()) {
//				total += adapter.getViewTypeCount();
//			}
//			return total;
//		}
//
//		public int getItemViewType(int position) {
//			int type = 1;
//			for (Object section : this.sections.keySet()) {
//				Adapter adapter = sections.get(section);
//				int size = adapter.getCount() + 1;
//
//				// check if position inside this section
//				if (position == 0) {
//					return TYPE_SECTION_HEADER;
//				}
//				if (position < size) {
//					return type + adapter.getItemViewType(position - 1);
//				}
//				// otherwise jump into next section
//				position -= size;
//				type += adapter.getViewTypeCount();
//			}
//			return -1;
//		}
//
//		public boolean areAllItemsSelectable() {
//			return false;
//		}
//
//		public boolean isEnabled(int position) {
//			return (getItemViewType(position) != TYPE_SECTION_HEADER);
//		}
//
//
//		@Override
//		public View getView(int position, View convertView, ViewGroup parent) {
//			int sectionnum = 0;
////			View mView = null;
////			LayoutInflater mInflater = LayoutInflater.from(mainActivity);
////			mView = mInflater.inflate(R.layout.list_spinner, parent, false);
//
//			for (Object section : this.sections.keySet()) {
//				Adapter adapter = sections.get(section);
//				int size = adapter.getCount() + 1;
//
//				// check if position inside this section
//				if (position == 0) {
//					return headers.getView(sectionnum, convertView, parent);
//				}
//				if (position < size) {
//					return adapter.getView(position - 1, convertView, parent);
//				}
//
//				// otherwise jump into next section
//				position -= size;
//				sectionnum++;
//			}
//			return null;
//		}
//
//		@Override
//		public long getItemId(int position) {
//			return position;
//		}
//		
//	}

	
	@Override
	public void onDestroy() {
		try {
			if (receiver != null) {
				mainActivity.unregisterReceiver(receiver);
			}
			if (avatarBitmap != null && avatarBitmap.get() != null && !avatarBitmap.get().isRecycled()) {
				avatarBitmap.get().recycle();
				avatarBitmap = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.onDestroy();
	}
	
	public class UpdateAvatarReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			UserTable ut = new UserTable(mainActivity);
			entry = ut.get();
			setUserinfoView();
		}
		
	}
	
}
